// src/stores/commonStore.ts
import { defineStore } from 'pinia';
import { reqSendVerificationCode, reqExportScores } from '@/api/common'; // 假设有一些API函数

let useCommonStore = defineStore('CommonStore', {
    state: () => ({
        loading: false,               // 加载状态
        error: null as string | null, // 错误信息
        successMessage: null as string | null, // 成功消息
    }),
    actions: {
        async sendVerificationCode(email: string) {
            console.log("发送验证码...");
            this.loading = true;
            try {
                const response = await reqSendVerificationCode(email);
                console.log("验证码发送了吗");
                console.log(response.code);
                console.log("验证码没问题")
                if (response.code == 200) {
                    this.successMessage = "验证码已发送，请查收邮件";
                    this.error = null;
                    return 'ok';
                } else {
                    return Promise.reject(new Error(response.message || "发送验证码失败"));
                }

            } catch (err) {
                console.error('Error sending verification code:', err);
                const error = err as any;
                this.error = error.response?.data?.message || 'Failed to send verification code';
            } finally {
                this.loading = false;
            }
        },

        async exportGroupsScores(classId: number) {
            console.log("导出成绩...");
            this.loading = true;
            try {
                const response = await reqExportScores(classId);
                console.log(response);

                if (response.code === 200) {
                    // 假设返回的是一个文件下载链接或直接触发文件下载
                    // window.location.href = response.data.downloadUrl; // 下载文件
                    this.successMessage = "成绩导出成功";
                    this.error = null;
                    return 'ok';
                } else {
                    return Promise.reject(new Error(response.message || "导出成绩失败"));
                }

            } catch (err) {
                console.error('Error exporting scores:', err);
                const error = err as any;
                this.error = error.response?.data?.message || 'Failed to export scores';
            } finally {
                this.loading = false;
            }
        },
    },
    getters: {
        // 可以在这里添加一些计算属性或派生状态
    }
});
export default useCommonStore